package com.pj.wisdomlogistics.utils;

import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.widget.Toast;

import com.pj.wisdomlogistics.ui.activity.PdfActivity;
import com.pj.wisdomlogistics.ui.view.NumberProgressDialog;

import java.io.File;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import zlc.season.rxdownload2.RxDownload;
import zlc.season.rxdownload2.entity.DownloadStatus;

/**
 * Created by WuFan on 2017/10/20.
 */

public class PdfDownload {
    public static NumberProgressDialog mNumberProgressDialog;

    public static void pdfDownload(final Context mContext , String currentStampUrl){
        //点击打开pdf盖章文件
        File pdf = new File(getDownloadDir(), "stamp.pdf");
        if (pdf.exists()) {
            pdf.delete();
        }

        mNumberProgressDialog = new NumberProgressDialog(mContext);
        mNumberProgressDialog.show();

        Disposable mDisposable = RxDownload.getInstance(mContext)
                .download(currentStampUrl, "stamp.pdf", getDownloadDir())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DownloadStatus>() {
                    @Override
                    public void accept(@NonNull DownloadStatus mDownloadStatus) throws Exception {
                        //mDownloadStatus为下载进度
                        mNumberProgressDialog.setProgress((int) mDownloadStatus.getPercentNumber());
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(@NonNull Throwable mThrowable) throws Exception {
                        //下载失败
                        mNumberProgressDialog.dismiss();
                        Toast.makeText(mContext, "PDF下载失败", Toast.LENGTH_SHORT).show();
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        //下载成功
                        mNumberProgressDialog.dismiss();
                        Toast.makeText(mContext, "PDF下载成功", Toast.LENGTH_SHORT).show();
                        Intent mIntent = new Intent(mContext , PdfActivity.class);
                        mContext.startActivity(mIntent);

                    }
                });
    }

    public static final String getDownloadDir() {
        File pbcDownload = new File(Environment.getExternalStorageDirectory(), "StampPdf");
        if (!pbcDownload.exists()) {
            pbcDownload.mkdir();
        }
        return pbcDownload.getAbsolutePath();
    }

}
